/*package com.utils.http;


import java.io.File;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.ConnectException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.SSLException;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import com.supers.enums.Method;
import com.supers.pojo.HttpRequest;
import com.supers.pojo.LogUtil;
import com.utils.transtype.JsonObjectUtil;
import com.utils.transtype.TransType;


 *
 *类名：HttpProtocolHandler
 *功能：HttpClient方式访问
 *详细：获取远程HTTP数据
 *版本：3.3
 *日期：2012-08-17
 
@SuppressWarnings("deprecation")
public class HttpClientPool extends LogUtil{
	private String contentType;
	private final static String json="application/json;charset=";//参数用字符串流
	private final static String form="application/x-www-form-urlencoded;charset=";//参数用form键值对
	public static HttpClientPool httpJson=new HttpClientPool(json);
	public static HttpClientPool httpForm=new HttpClientPool(form);
	
	//默认编码
	private  static String              DEFAULT_CHARSET                 = "UTF-8";
	设置Socket最大等待时间（单位是毫秒）,socket等待时间是指从站点下载页面和数据时，
	 * 两个数据包之间的最大时间间隔，超过这个时间间隔，httpclient就认为连接出了故障
    private  static int                        socketTimeout            = 3000;

    设置连接最大等待时间（单位是毫秒）,连接最大等待时间则是指和站点建立连接时的最
     * 大等待时间， 超过这个时间站点不给回应，则认为站点无法连接
    private  static int                        connectionTimeout        = 4000;
   
    
	public HttpClientPool(String contentType) {
		super();
		this.contentType = contentType;
	}


	    
	 * 设置httpclient是否使用NoDelay策略。如果启用了NoDelay策略，httpclient和站点之间传输数据
	 * 时将会尽可能及时地将发送缓冲区中的数据发送出去、而不考虑网络带宽的利用率，这个策略适合对实
	 * 时性要求高的场景。而禁用了这个策略之后，数据传输会采用Nagle's algorithm发送数据，该算法会
	 * 充分顾及带宽的利用率，而不是数据传输的实时性
	  
    private static boolean                    TCP_NODELAY        		= false;
    
    //设置socket缓冲区的大小（单位为字节），默认是8KB。
    private static int                        SOCKET_BUFFER_SIZE      = 1024 * 1024;//1m
    
    //每个路由上的最大连接个数
    private static int                        DefaultMaxPerRoute       = 20;
    //设置连接池的最大连接数
    private  static int                        MaxTotal                 =200;
    //失败最大重连次数
    private static int                        retryTime                  =3;
    

    *//**
     * HTTP连接池，该连接管理器必须是线程安全的.
     *//*
	private static PoolingClientConnectionManager   connectionManager;
    private static DefaultHttpClient httpclient;

    
    *//**
     * 执行Http请求
     * 
     * @param request 请求数据
     * @param strParaFileName 文件类型的键值
     * @param strFilePath 文件路径
     * @return 
     * @throws Exception 
     * @throws FileNotFoundException 
     * @throws HttpException, IOException 
     *//*
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public <T> Object callRest(HttpRequest request, Class<T> responseClazz) throws Exception {
		String result;
		String charset=request.getCharset()==null?DEFAULT_CHARSET:request.getCharset();
		HttpUriRequest httpRequest;
		if (request.getHttpRoute()!=null) {
			connectionManager.setMaxPerRoute(request.getHttpRoute(), request.getHttpRouteMax());
		}
		if (request.getMethod().equals(Method.GET)) {
			//get请求,url为拼接参数的链接
			httpRequest=new HttpGet(request.getUrl());
		}else {
			//post请求
			httpRequest= new HttpPost(request.getUrl());
			Object postParam=request.getPostParam() ;
			if (contentType.equals(json)) {
				//字符串流传递
				String jsonData = JsonObjectUtil.ALWAYS.objectToJson(postParam);			
				if (request.getStrFilePath().equals("") && request.getStrParaFileName().equals("")) {
					//无文件
					StringEntity input = new StringEntity(jsonData,charset);
					((HttpPost)httpRequest).setEntity(input);
				}else {
					//有文件	              
					 FileBody bin = new FileBody(new File(request.getStrFilePath()));  	                		              
			         StringBody content = new StringBody(jsonData.toString());  		  
			         MultipartEntity reqEntity = new MultipartEntity();  	
			         reqEntity.addPart(request.getStrParaFileName(), bin);//添加文件，通过 request.getStrParaFileName()为参数名称
			         reqEntity.addPart("jsonStr", content);//jsonStr为请求后台的普通参数   
			         ((HttpPost)httpRequest).setEntity(reqEntity);  			              
				}
			} else {
				//键值对传递
				Map<String, Object> map=TransType.beanToMap(postParam);
				Iterator iterator = map.entrySet().iterator();  
		        if (request.getStrFilePath().equals("") && request.getStrParaFileName().equals("")) {
		        	//无文件
		        	List<NameValuePair> list = new ArrayList<NameValuePair>();  
		        	while(iterator.hasNext()){  
		        		Entry<String,String> elem = (Entry<String, String>) iterator.next();  
		        		list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));  
		        		
		        	}  
		        	if(list.size() > 0){  
			             UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset.toString());  
			             ((HttpPost)httpRequest).setEntity(entity);  
			        }
				}else {
					//有文件	              
					 FileBody bin = new FileBody(new File(request.getStrFilePath()));  	
					 MultipartEntity reqEntity = new MultipartEntity();  	
					 while(iterator.hasNext()){  
			        		Entry<String,String> elem = (Entry<String, String>) iterator.next();  
			        		reqEntity.addPart(elem.getKey(), new StringBody(elem.getValue()));//添加参数键值对		        		
					 }  
			         reqEntity.addPart(request.getStrParaFileName(), bin);//添加文件，通过 request.getStrParaFileName()为参数名称
			         ((HttpPost)httpRequest).setEntity(reqEntity);  			              
				}		        
			}
			
		}		
		httpRequest=setHead(httpRequest,charset);
		HttpResponse response =httpclient.execute(httpRequest);
		response=getResponse(response);
		HttpEntity httpEntity = response.getEntity();  
        result = EntityUtils.toString(httpEntity);//取出应答字符串  
        result.replaceAll("\r", "");//去掉返回结果中的"\r"字符，否则会在结果字符串后面显示一个小方格   
		if (("".equals(result)) || (result == null)) {
			return null;
		}
		log.info("response string : " + result.toString());
		if (responseClazz!=null) {
			return JsonObjectUtil.ALWAYS.jsonToObject(result, responseClazz);
		}else {
			return null;
		}
	}
    
   
    
    
    
    //设置请求头信息
    private  HttpUriRequest setHead(HttpUriRequest request,String charset) {
    	request.setHeader("Content-Type", contentType+charset);
    	request.addHeader("Accept-Encoding", "gzip"); //设置数据压缩传递
    	request.addHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.160 Safari/537.22");//设置代理
    	return request;
	}
    
    
    //对返回数据判断是否压缩，压缩则解压缩
    private  HttpResponse  getResponse(HttpResponse response ) {
    	HttpEntity entity = response.getEntity();  
    	Header header = entity.getContentEncoding();  
    	if (header != null)  
    	{  
    	    HeaderElement[] codecs = header.getElements();  
    	    for (int i = 0; i < codecs.length; i++)  
    	    {  
    	        if (codecs[i].getName().equalsIgnoreCase("gzip"))  
    	        {  
    	            response.setEntity(new GzipDecompressingEntity(entity));  
    	        }  
    	    }  
    	}  
    	return response;  
	}
    
    
    
    
    
    
    
    *//**
     * 初始化数据.
     *//*

      static{
		// 创建一个线程安全的HTTP连接池
    	SchemeRegistry schemeRegistry = new SchemeRegistry();  
        schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));  //注册http协议的默认端口号
        schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));  //注册https协议的默认端口号
        connectionManager = new PoolingClientConnectionManager(schemeRegistry);
        connectionManager.setMaxTotal(MaxTotal);
        connectionManager.setDefaultMaxPerRoute(DefaultMaxPerRoute);  //每个路由上的默认连接个数
        HttpHost googleResearch = new HttpHost("research.google.com", 80);
        connectionManager.setMaxPerRoute(new HttpRoute(googleResearch), 50); //单独为某个站点设置最大连接个数  
        // httpclient初始化
        httpclient = new DefaultHttpClient(connectionManager);
        httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, socketTimeout); //Socket最大等待时间 
        httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); //连接最大等待时间（单位都是毫秒） 
        httpclient.getParams().setParameter(CoreConnectionPNames.TCP_NODELAY, TCP_NODELAY);  
        httpclient.getParams().setParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, SOCKET_BUFFER_SIZE);  
        HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler()  
        {  
            @Override  
            public boolean retryRequest(IOException exception, int executionCount, HttpContext context)  
            {  
                if (executionCount >= retryTime)  
                {  
                    // Do not retry if over max retry count  
                    return false;  
                }  
                if (exception instanceof InterruptedIOException)  
                {  
                    // Timeout  
                    return false;  
                }  
                if (exception instanceof UnknownHostException)  
                {  
                    // Unknown host  
                    return false;  
                }  
                if (exception instanceof ConnectException)  
                {  
                    // Connection refused  
                    return false;  
                }  
                if (exception instanceof SSLException)  
                {  
                    // SSL handshake exception  
                    return false;  
                }  
                HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);  
                boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);  
                if (idempotent)  
                {  
                    // Retry if the request is considered idempotent  
                    return true;  
                }  
                return false;  
            } 
          
        };  
        httpclient.setHttpRequestRetryHandler(myRetryHandler);  
	}









   

   
}
*/